<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>企业微信信息化平台</title>
    <link rel="stylesheet" th:href="@{/layui/css/layui.css}">
    <link rel="stylesheet" th:href="@{/index.css}">
    <link rel="stylesheet" th:href="@{/vendors/mdi/css/materialdesignicons.min.css}">
    <link rel="stylesheet" th:href="@{/vendors/base/vendor.bundle.base.css}">
</head>
<body>
<div id="app">
    <div class="layui-btn-group">
        <button type="button" class="layui-btn layui-btn-normal" id="lastPeriod"
                onclick="periodChange(this.id)">前一天
        </button>
        <button type="button" class="layui-btn layui-btn-normal" id="nextPeriod"
                onclick="periodChange(this.id)">后一天
        </button>
        <button type="button" class="layui-btn layui-btn-normal"
                onclick="isGroupDisplay()">是否显示部门
        </button>
        <button type="button" class="layui-btn layui-btn-primary" id="tbSortDesc"
                onclick="tbSortDesc(this.id)">降序
        </button>
    </div>
    <div class="container-fluid">
        <div class="layui-col-md6">
            <div class="page-item" id="tb_div2">

            </div>

        </div>
        <div class="layui-col-md3">
            <div class="layui-card">
                <div class="layui-card-header">群数据介绍</div>
                <div class="layui-card-body">
                    <table class="layui-table">
                        <tr>
                            <td>群总数:</td>
                            <td><span class="layui-badge" id="all_group_cnt"></span></td>
                        </tr>
                        <tr>
                            <td>销售部门群总数:</td>
                            <td><span class="layui-badge layui-bg-orange" id="seller_group_cnt"></span></td>
                        </tr>
                        <tr>
                            <td>昨日活跃群数量:</td>
                            <td><span class="layui-badge layui-bg-cyan" id="yesterday_live_group_cnt"></span></td>
                        </tr>
                        <tr>
                            <td>昨日新增群数量:</td>
                            <td><span class="layui-badge layui-bg-green" id="yesterday_new_group_cnt"></span></td>
                        </tr>
                    </table>
                </div>
                <div class="layui-card-header">群数据介绍(销售部门群总数)</div>
                <div class="layui-card-body">
                    <div class="layui-btn-group">
                        <button type="button" class="layui-btn layui-btn-normal" id="lastWeek"
                                onclick="periodChange(this.id)">前一周
                        </button>
                        <button type="button" class="layui-btn layui-btn-normal" id="nextWeek"
                                onclick="periodChange(this.id)">后一周
                        </button>
                    </div>
                    <div class="page-item" id="tb_week_seller_div">

                    </div>
                </div>
            </div>
        </div>
    </div>

</div>

<script th:src="@{/layui/jquery-3.6.0.min.js}"></script>
<script th:src="@{/layui/layui.js}"></script>


<script>
    let optionData = {
        options: 'SwitchPeriod',
        switchPeriod: {
            period: 'month',
            month: 0,
            week: 0
        },
        customTime: {
            startTime: null,
            endTime: null
        }
    }

    let weekCount = 6;
    let period = 0;
    let weekPeriod = 0;

    /*请求某天的数据*/
    function periodChange(clickId) {
        if (clickId === 'lastPeriod') {
            period--;
            getDataAjax();
        } else if (clickId === 'nextPeriod') {
            if (period < 0) {
                period++;
                getDataAjax();
            } else {
                layui.use('layer', function () {
                    layer.msg("只能获取到昨天以前的数据哦")
                })
            }
        } else if (clickId === 'nextWeek') {
            if (weekPeriod === 0) {
                layui.use('layer', function () {
                    layer.msg("只能获取到昨天以前的数据哦")
                })
            } else {
                weekPeriod++
                getWeekSellerDataAjax()
            }
        } else if (clickId === 'lastWeek') {
            weekPeriod--
            getWeekSellerDataAjax()
        }
    }

    /*获取数据*/
    function getDataAjax() {
        $.ajax({
            url: "/getGroupLiveSevenDays",
            type: "get",
            data: {
                diff: period
            },
            dataType: "json",
            contentType: "application/json;charset=utf-8",
            success: function (data) {
                // addMessage(data);
                // addSellerDataToDiv(data['sellerData'])
                sellerDataTemp = data
                parseSellerData()
            }
        })
    }


    /*获取销售周数据*/
    function getWeekSellerDataAjax() {
        $.ajax({
            url: "/getWeekSellerData",
            type: "get",
            data: {
                diff: weekPeriod
            },
            dataType: "json",
            contentType: "application/json;charset=utf-8",
            success: function (data) {
                console.log(data)
                tb_week_seller_data.allData = data
                addWeekSellerTable(tb_week_seller_data)
            }
        })
    }

    function addWeekSellerTable() {
        let elementById = document.getElementById(tb_week_seller_data.id);

        let tb_temp = `<table class="` + tb_week_seller_data.tb_class + `">`;

        let title_ele = `<tr >`
        for (let titleElement of tb_week_seller_data.title) {
            // let temp=titleElement.key === 'memberHasMsg' ? 'width="20%"' : ``
            title_ele += `<th class="` + titleElement.class + ` tb_head" id="` + titleElement.key + `">` + titleElement.value + `</th>`
        }
        title_ele += `</tr>`

        for (const allDatum of tb_week_seller_data.allData) {
            title_ele += `<tr>`
            for (let i = 0; i < tb_week_seller_data.title.length; i++) {
                console.log(tb_week_seller_data.title[i])
                title_ele += `<td>` + allDatum[tb_week_seller_data.title[i].key] + `</td>`
            }
            title_ele += `</tr>`
        }
        console.log(title_ele)
        tb_temp += title_ele + `</table>`
        elementById.innerHTML = tb_temp
    }

    let tb_week_seller_data = {
        "id": "tb_week_seller_div",
        "sort": {
            "key": "chatTotal",
            "sort": false
        },
        "tb_class": "layui-table",
        "title": [{
            "key": "dayTime",
            "value": "日期",
            "class": "layui-bg-red"
        },
            {
                "key": "chatTotal",
                "value": "总群数",
                "class": "layui-bg-cyan"
            }, {
                "key": "newChatCnt",
                "value": "新增群",
                "class": "layui-bg-cyan"
            }, {
                "key": "chatHasMsg",
                "value": "活跃群",
                "class": "layui-bg-cyan"
            }],
        "group": [],
        "isGroupDisplay": false,
        allData: {}
    }


    /*填充表格的初始化参数*/
    let tb_obj_data = {
        "id": "tb_div2",
        "sort": {
            "key": "chat_total",
            "sort": false
        },
        "tb_class": "layui-table",
        "title": [{
            "key": "name",
            "value": "姓名",
            "class": "layui-bg-red"
        }, {
            "key": "chat_total",
            "value": "群总数",
            "class": "layui-bg-orange"
        },
            {
                "key": "new_chat_cnt",
                "value": "新增群",
                "class": "layui-bg-green"
            }, {
                "key": "st",
                "value": "1",
                "class": "layui-bg-cyan"
            }, {
                "key": "nd",
                "value": "2",
                "class": "layui-bg-cyan"
            }, {
                "key": "rd",
                "value": "3",
                "class": "layui-bg-cyan"
            }, {
                "key": "fo",
                "value": "4",
                "class": "layui-bg-cyan"
            }, {
                "key": "fi",
                "value": "5",
                "class": "layui-bg-cyan"
            }, {
                "key": "si",
                "value": "6",
                "class": "layui-bg-cyan"
            }, {
                "key": "se",
                "value": "7",
                "class": "layui-bg-cyan"
            }],
        "group": [],
        "isGroupDisplay": true,
        allData: {}
    }

    /*ajax获取到的销售数据存放点*/
    let sellerDataTemp = {}

    /*是否显示群组名*/
    function isGroupDisplay() {
        tb_obj_data.isGroupDisplay = !tb_obj_data.isGroupDisplay
        parseSellerData();
    }

    function tbSortDesc(id) {
        let elementById = document.getElementById(id);
        if (tb_obj_data.sort.sort) {
            tb_obj_data.sort.sort = false
            elementById.innerText = `降序`

        } else {
            tb_obj_data.sort.sort = true
            elementById.innerText = `升序`
        }
        parseSellerData()
    }

    /*求和*/
    function getSum(key1, key2, key3, ary) {
        return ary.reduce((pre, next) => {
            pre[key1] = (pre[key1] || 0) + (next[key1] || 0)
            pre[key2] = (pre[key2] || 0) + (next[key2] || 0)
            pre[key3] = (pre[key3] || 0) + (next[key3] || 0)
            return pre
        }, {})
    }

    function group_data_description() {
        let all_group_cnt = document.getElementById("all_group_cnt");
        let seller_group_cnt = document.getElementById("seller_group_cnt");
        let yesterday_live_group_cnt = document.getElementById("yesterday_live_group_cnt");
        let yesterday_new_group_cnt = document.getElementById("yesterday_new_group_cnt");
        all_group_cnt.innerHTML = sellerDataTemp['allGroupCnt']
        seller_group_cnt.innerHTML = tb_obj_data.allData['chat_total']
        yesterday_live_group_cnt.innerHTML = tb_obj_data.allData['st']
        yesterday_new_group_cnt.innerHTML = tb_obj_data.allData['new_chat_cnt']
    }


    /*解析数据*/
    function parseSellerData() {
        console.log(sellerDataTemp)
        let data = sellerDataTemp;
        let datum = data['sellerData'];
        for (const allKey in datum) {
            tb_obj_data.title[0]['value'] = allKey;
            data["date"].forEach((value, index) => {
                tb_obj_data.title[index + 3].value = value
            })
            tb_obj_data.group = []

            /*计算全部数据，以及不显示群组头部总数据*/
            let allDataTempList = []
            for (const groupKey in datum[allKey]) {
                if (groupKey !== 'remark') {
                    allDataTempList = allDataTempList.concat(datum[allKey][groupKey])
                }
            }
            /*拿到数据赋值*/
            tb_obj_data.allData = getSum('chat_total', 'st', 'new_chat_cnt', allDataTempList);
            /*更新到页面*/
            group_data_description();
            if (tb_obj_data.isGroupDisplay) {
                for (const groupKey in datum[allKey]) {
                    if (groupKey !== 'remarked') {
                        let tempGroupData = {
                            "head": [{
                                "name": groupKey
                            }, {
                                "name": "平均"
                            }],
                            "context": datum[allKey][groupKey]
                        }
                        tb_obj_data.group.push(tempGroupData)
                    }
                }
            } else {
                let tempGroupData = {
                    "head": [{
                        "name": "合计"
                    }, {
                        "name": "平均"
                    }
                    ],
                    "context": allDataTempList
                }
                tb_obj_data.group.push(tempGroupData)
            }
        }
        addTable(tb_obj_data)
    }

    /*比较父级*/
    function compareParent(p, desc) { //这是比较函数,比较二级头
        return function (m, n) {
            let a = m["head"][0][p];
            let b = n["head"][0][p];
            if (desc) {
                return a - b;
            } else {
                return b - a; //降序
            }
        }
    }

    /*比较子集*/
    function compareSon(p, desc) {
        return function (m, n) {
            let a = m[p];
            let b = n[p];
            if (desc) {
                return a - b;
            } else {
                return b - a; //降序
            }
        }
    }

    /*入口*/
    function addTable(tb_object) {
        /*填充组头数据*/
        if (tb_object['group'] !== undefined) {
            let groups = tb_object['group'];
            groups.forEach((groupsValue, groupsKey) => {
                groupsValue.context.sort(compareSon(tb_object.sort.key, tb_object.sort.sort))
                /*遍历组头（组头可能有多个）*/
                groupsValue.head.forEach((headValue, headKey) => {
                    /*遍历表头，拿到key获取组头的对应值*/
                    tb_object.title.forEach((tb_title_value) => {
                        /*组头的当前值*/
                        let temp = headValue[tb_title_value.key];
                        /*组头的临时值*/
                        let tempGroupValue = 0;
                        /*如果组头的当前值为空，则为组头赋值*/
                        if (temp === undefined || temp === '' || temp === null) {
                            groupsValue.context.forEach((contextValue) => {
                                tempGroupValue += contextValue[tb_title_value.key]
                            })
                            if (headKey === 0) {
                                // tb_obj_data.allData[tb_title_value.key]=tempGroupValue
                                tb_object.group[groupsKey].head[headKey][tb_title_value.key] = tempGroupValue
                            } else {
                                tb_object.group[groupsKey].head[headKey][tb_title_value.key] = (tempGroupValue / groupsValue.context.length).toFixed(2);
                            }
                        }
                    })
                })
            })
        } else {
            return;
        }
        tb_object.group.sort(compareParent(tb_object.sort.key, tb_object.sort.sort));
        creatTable(tb_object);
    }

    /*添加表头排序事件*/
    document.body.onclick = function (event) {
        let id = event.target.id;
        for (let tbHead of tb_obj_data.title) {
            if (tbHead.key === id) {
                tb_obj_data.sort.key = id
                // tb_obj_data.sort.sort = !tb_obj_data.sort.sort
                addTable(tb_obj_data)
                return
            }
        }
    }

    /*数据解析并加入到dom*/
    function creatTable(table_object) {
        let title, groups, title_ele = ``, group_ele = ``, id;
        if (table_object['id'] !== undefined) {
            id = table_object['id'];
        } else {
            return;
        }
        title_ele += `<table class="` + table_object.tb_class + `">`;
        if (table_object['title'] !== undefined) {
            title = table_object['title'];
            title_ele += `<tr >`
            for (let titleElement of title) {
                title_ele += `<th class="` + titleElement.class + ` tb_head" id="` + titleElement.key + `">` + titleElement.value + `</th>`
            }
            title_ele += `</tr>`
        } else {
            return;
        }
        if (table_object['group'] !== undefined) {
            groups = table_object['group'];
            for (let group of groups) {
                for (let headElement of group.head) {
                    group_ele += `<tr class="layui-bg-black">`
                    for (let titleElement of title) {
                        group_ele += `<td class="` + titleElement.class + `">` + headElement[titleElement.key] + `</td>`
                    }
                    group_ele += `</tr>`
                }
                // console.log(contexts.context)
                for (let contextElement of group.context) {
                    // console.log(contextElement)
                    group_ele += `<tr>`
                    /*遍历表头，获取一行每一单元格的值*/
                    for (let titleElement of title) {
                        group_ele += `<td>`
                            + contextElement[titleElement.key]
                            + `</td>`
                    }
                    group_ele += `</tr>`
                }
            }
            title_ele += group_ele;
        } else {
            return;
        }
        title_ele += `</table>`;
        let elementById = document.getElementById(id);
        elementById.innerHTML = title_ele;
    }

    function dataChange(clickId) {
        optionData.options = 'SwitchPeriod';
        switch (clickId) {
            case 'nextMonth':
                optionData.switchPeriod.month++;
                optionData.switchPeriod.period = 'month';
                break;
            case 'lastMonth':
                optionData.switchPeriod.month--;
                optionData.switchPeriod.period = 'month';
                break;
            case 'nextWeek':
                if (optionData.switchPeriod.week < weekCount) {
                    optionData.switchPeriod.week++;
                    optionData.switchPeriod.period = 'week';
                }
                break;
            case 'lastWeek':
                if (optionData.switchPeriod.week > 1) {
                    optionData.switchPeriod.week--;
                    optionData.switchPeriod.period = 'week';
                }
                break;
            case 'now':
                break;
            default:
                console.log('error')
        }
        clientData(optionData)
    }

    function clientData(data) {
        console.log(data)
        $.ajax({
            url: "/getGroupLiveSevenDays",
            type: "get",
            data: {
                dataOption: JSON.stringify(data)
            },
            dataType: "json",
            contentType: "application/json;charset=utf-8",
            success: function (data) {
                addMessage(data);

            }
        })
    }

    /*向div中填充表格*/
    function addSellerDataToDiv(sellerData) {
        let tempHtml = ``;
        console.log(sellerData)
        for (let sellerDatum in sellerData) {
            console.log('日期：' + sellerDatum)
            tempHtml += `<table class="layui-table">
                            <tr>
                                <th class="layui-bg-red">` + sellerDatum + `</th>
                                <th class="layui-bg-orange">群总数</th>
                                <th class="layui-bg-green">新增群</th>
                            </tr>`
            for (let sellerDatumKey in sellerData[sellerDatum]) {
                console.log('部门：' + sellerDatumKey)

                let departmentHtml = ``;
                let chat_total = 0;
                let new_chat_cnt = 0;
                /*部门遍历*/
                for (const sellerDatumElementKey in sellerData[sellerDatum][sellerDatumKey]) {
                    /*部门人员数组遍历*/
                    if (sellerDatumKey === 'remark') {
                        continue;
                    }
                    console.log(sellerData[sellerDatum][sellerDatumKey][sellerDatumElementKey]['name'])

                    departmentHtml += `<tr><td>` + sellerData[sellerDatum][sellerDatumKey][sellerDatumElementKey]['name'] + `</td>`;
                    for (let sellerDatumElementElementKey in
                        sellerData[sellerDatum][sellerDatumKey][sellerDatumElementKey]) {
                        // console.log(sellerDatumElementElementKey)
                        // console.log(sellerData[sellerDatum][sellerDatumKey][sellerDatumElementKey][sellerDatumElementElementKey])
                        if (sellerDatumElementElementKey !== 'URemark' &&
                            sellerDatumElementElementKey !== 'day_time' &&
                            sellerDatumElementElementKey !== 'name') {
                            departmentHtml += `<td>` +
                                sellerData[sellerDatum][sellerDatumKey][sellerDatumElementKey][sellerDatumElementElementKey] + `</td>`
                            if (sellerDatumElementElementKey === 'new_chat_cnt') {
                                new_chat_cnt += sellerData[sellerDatum][sellerDatumKey][sellerDatumElementKey][sellerDatumElementElementKey];
                            } else if (sellerDatumElementElementKey === 'chat_total') {
                                chat_total += sellerData[sellerDatum][sellerDatumKey][sellerDatumElementKey][sellerDatumElementElementKey];
                            }
                        }
                    }
                    departmentHtml += `</tr>`
                }
                if (sellerDatumKey !== 'remark') {
                    tempHtml += `<tr class="layui-bg-cyan"><td >` + sellerDatumKey + `</td><td>` + chat_total + `</td><td>` + new_chat_cnt + `</td></tr>`
                    tempHtml += departmentHtml;
                }
            }
        }
        tempHtml += `</table>`
        let elementById = document.getElementById("tb_div1");
        elementById.innerHTML = tempHtml;
    }

    function addMessage(data) {
        let sellerData = data['items'];
        let elementById = document.getElementById('tb_div');
        let tempHtml = '<table class="layui-table">'
        for (let sellerDataKey in sellerData) {
            if (sellerDataKey === '其他' || sellerDataKey === '代理') {
                continue;
            }
            tempHtml += `<tr><td>` + sellerDataKey + `</td></tr>`
            for (let sellerDatumKey in sellerData[sellerDataKey]) {
                tempHtml += '<tr>'
                for (let sellerDatumElementKey in sellerData[sellerDataKey][sellerDatumKey]) {
                    if (sellerDatumElementKey === 'UOwner'
                        || sellerDatumElementKey === 'UDepartment'
                        || sellerDatumElementKey === 'URemark'
                        || sellerDatumElementKey === 'UPosition') {
                        continue;
                    }
                    tempHtml += `<td>` + sellerData[sellerDataKey][sellerDatumKey][sellerDatumElementKey] + '</td>'
                }
                tempHtml += '</tr>'
            }

        }
        elementById.innerHTML += tempHtml
    }

    getDataAjax()
    getWeekSellerDataAjax()
</script>
<script th:src="@{/js/vue/vue.js}"></script>
<script th:src="@{/js/off-canvas.js}"></script>
<script th:src="@{/js/hoverable-collapse.js}"></script>
<script th:src="@{/js/template.js}"></script>
</body>
</html>
